import axios from 'axios'
import { MessageBox, Message } from 'element-ui'
import store from '@/store'
import { getToken } from '@/utils/auth'
import router from '../router'
// import Vue from 'vue'

// const port = window.localStorage.getItem('port') ? window.localStorage.getItem('port') : '8086'
// if (!window.localStorage.getItem('port')) {
//   window.localStorage.setItem('port', '8086')
//   window.localStorage.setItem('name', '天津铜盟')
// }
var service = {}
// create an axios instance
service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API + process.env.VUE_APP_API,
  // withCredentials: true, // send cookies when cross-domain requests
  timeout: 30000
})

const isFormData = (obj) => {
  return typeof obj === 'object' && obj instanceof FormData;
}

// request interceptor
service.interceptors.request.use(
  config => {
    // if(config.data && config.data.updateTime === null) config.data.updateTime = ''
    // if(isFormData(config.data)){
    //   if(config.data.get('updateTime') === null || config.data.get('updateTime') === 'null'){
    //     config.data.set('updateTime','')
    //   }
    // }
    // do something before request is sent
    // console.log('222', store.getters)
    if (store.getters.token) {
      // let each request carry token
      // ['X-Requested-Token'] is a custom headers key
      // please modify it according to the actual situation
      config.headers['satoken'] = getToken()
    }
    // config.headers['Content-Type'] = 'application/x-www-form-urlencoded'
    return config
  },
  error => {
    // do something with request error
    return Promise.reject(error)
  }
)

// response interceptor
service.interceptors.response.use(
  /**
   * If you want to get http information such as headers or status
   * Please return  response => response
  */

  /**
   * Determine the request status by custom code
   * Here is just an example
   * You can also judge the status by HTTP Status Code
   */
  response => {
    // 未设置状态码则默认成功状态
    const code = response.data.code || 200;
    const isSuccess = response.data.isSuccess;
    // 获取错误信息
    const msg = response.data.msg

    if (code !== 200) {
      if(code != undefined){
        Message({
          message: msg || 'Error',
          type: 'error',
          duration: 5000
        })
      }
      // 50008: Illegal token; 50012: Other clients logged in; 50014: Token expired;
      if (code === 201) {
        // to re-login
        MessageBox.confirm('You have been logged out, you can cancel to stay on this page, or log in again', 'Confirm logout', {
          confirmButtonText: 'Re-Login',
          cancelButtonText: 'Cancel',
          type: 'warning'
        }).then(() => {
          store.dispatch('user/resetToken').then(() => {
            location.reload()
          })
        })
      }
      return Promise.reject(response.data)
    } else {
      return response.data.data
    }
  },
  error => {
    if (error && error.response && error.response.status === 403 && router.currentRoute.fullPath !== '/login') {
      Message({
        message: '账号登录过期请重新登录',
        type: 'error',
        duration: 5 * 1000
      })
      return Promise.reject(error)
    } else if (error && error.response && error.response.status !== 403) {
      Message({
        message: error.message,
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
)

export default service
